package com.huarui.saleOrder.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.code.dao.ICodeGenericDao;
import com.huarui.code.model.CodeGeneric;
import com.huarui.company.dao.ICompanyDao;
import com.huarui.company.model.Company;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.dictionary.service.DictionaryReadOnlyService.DictionaryResource;
import com.huarui.notice.INoticeService;
import com.huarui.notice.Notice;
import com.huarui.params.Params;
import com.huarui.partner.dao.IPartnerAddressDao;
import com.huarui.partner.dao.IPartnerDao;
import com.huarui.partner.model.Partner;
import com.huarui.partner.model.PartnerAddress;
import com.huarui.purchaseOrder.model.PurOrSaleOrder;
import com.huarui.purchaseOrder.model.PurOrSaleOrderDetail;
import com.huarui.purchaseOrder.service.PurOrSaleTaskService;
import com.huarui.receiptAddress.dao.IReceiptAddressDao;
import com.huarui.receiptAddress.model.ReceiptAddress;
import com.huarui.saleOrder.dao.ISaleOrderDao;
import com.huarui.saleOrder.dao.ISaleOrderDetailsDao;
import com.huarui.saleOrder.enums.SaleOrderFunctionEnum;
import com.huarui.saleOrder.enums.SaleOrderOperateMesEnum;
import com.huarui.task.model.Task;
import com.huarui.task.service.TaskEngineService;
import com.huarui.task.taskEnum.BehaviourEnum;
import com.huarui.task.taskEnum.WorkFlowTaskNameEnum;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.FuncUtil;

/**
 * 
 * @author ycf
 *
 */
public class SaleOrderService extends BaseService{
	private ISaleOrderDetailsDao saleOrderDetailsDao;

	private IPartnerDao partnerDao;
	
	private IPartnerAddressDao partnerAddressDao;
	
//	private IReceiptAddressDao receiptAddressDao;
	
	private ICompanyDao companyDao;
	
	private ICodeGenericDao codeGenericDao;
	
//	private TaskEngineService taskEngineService;
	
//	private DictionaryReadOnlyService dictionaryReadOnlyService;
	
	private PurOrSaleTaskService purOrSaleTaskService;
	
	private INoticeService noticeService;
	
	private Logger logger = Logger.getLogger(SaleOrderService.class);
	
	public void setCompanyDao(ICompanyDao companyDao) {
		this.companyDao = companyDao;
	}

	public void setPartnerDao(IPartnerDao partnerDao) {
		this.partnerDao = partnerDao;
	}

//	public void setReceiptAddressDao(IReceiptAddressDao receiptAddressDao) {
//		this.receiptAddressDao = receiptAddressDao;
//	}

	public void setPartnerAddressDao(IPartnerAddressDao partnerAddressDao) {
		this.partnerAddressDao = partnerAddressDao;
	}

	public void setSaleOrderDetailsDao(ISaleOrderDetailsDao saleOrderDetailsDao) {
		this.saleOrderDetailsDao = saleOrderDetailsDao;
	}
	
	public void setCodeGenericDao(ICodeGenericDao codeGenericDao) {
		this.codeGenericDao = codeGenericDao;
	}

	private ISaleOrderDao getDao() {
		return (ISaleOrderDao) super.dao;
	}
	
//	public void setDictionaryReadOnlyService(
//			DictionaryReadOnlyService dictionaryReadOnlyService) {
//		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
//	}

	public void setNoticeService(INoticeService noticeService) {
		this.noticeService = noticeService;
	}

//	public void setTaskEngineService(TaskEngineService taskEngineService) {
//		this.taskEngineService = taskEngineService;
//	}

	public void setPurOrSaleTaskService(PurOrSaleTaskService purOrSaleTaskService) {
		this.purOrSaleTaskService = purOrSaleTaskService;
	}

	/**
	 * 新增销售订单设置业务伙伴
	 * @param partnerId
	 * @param orders
	 * @return
	 */
	private boolean insertPartnerToOrders(Integer partnerId, PurOrSaleOrder orders) {
		Partner p = (Partner) partnerDao.getById(partnerId);
		if(p == null) {
			logger.error("新增销售订单时卖方业务伙伴不存在");
			return false;
		}
		
		orders.setPartnerIdBySeller(p.getId());
		orders.setPartnerNameBySeller(p.getName());
		orders.setPartnerPyCodeBySeller(p.getPyCode());
		orders.setBuyerId(null);
		orders.setBuyerName(null);
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> insertSaleOrderAndDetails(final PurOrSaleOrder saleOrder, 
			final List<PurOrSaleOrderDetail> saleDetailsList) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final String sellerName = se.getCompanyName();
		final Integer userId = se.getUserId();
		final String userName = se.getUserName();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status) {
					
					/*if(saleOrder.getBuyerId() != null && saleOrder.getBuyerId() != 0) {
						saleOrder.setWorkFlowId(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_SALE_ORDER.getWorkFlowId());
					} else {
						saleOrder.setWorkFlowId(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_SALE_ORDER.getWorkFlowId());
					}*/
//					System.out.println(saleOrder.getWorkFlowId() + "  .......");
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					
					if( !PurOrSaleOrder.STATUS_TMP.equals(saleOrder.getStatus()) && 
							!PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, null, true);
						return paramsMap;
					}
					
					String codeOfSeller = codeGenericDao.getNewCode(sellerId, CodeGeneric.SALE_ORDER);
					saleOrder.setCodeOfSeller(codeOfSeller);
					saleOrder.setCreatorId(userId);
					saleOrder.setCreatorName(userName);
					saleOrder.setCreatorCompanyId(sellerId);
					saleOrder.setCreatorCompanyName(sellerName);
					saleOrder.setSellerId(sellerId);
					saleOrder.setSellerName(sellerName);
					
					if(saleOrder.getBuyerId() != null) {
						Company buyer = (Company) companyDao.getById(saleOrder.getBuyerId());
						if(buyer != null) {
							saleOrder.setBuyerName(buyer.getName());
						}
					}
					
					if(PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())) {
						saleOrder.setSubmitterId(userId);
						saleOrder.setSubmitterName(userName);
						saleOrder.setCurrentorId(null);
						saleOrder.setCurrentorName(null);
						if(saleOrder.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_SALE_ORDER.getWorkFlowId())) {
							saleOrder.setCurrentCompanyId(sellerId);
							saleOrder.setCurrentCompanyName(sellerName);
						} else {
							saleOrder.setCurrentCompanyId(saleOrder.getBuyerId());
							saleOrder.setCurrentCompanyName(saleOrder.getBuyerName());
						}
					} else{
						saleOrder.setCurrentorId(userId);
						saleOrder.setCurrentorName(userName);
						saleOrder.setCurrentCompanyId(sellerId);
						saleOrder.setCurrentCompanyName(sellerName);
					}
					
					Partner partner = (Partner) partnerDao.getById(saleOrder.getPartnerIdBySeller());
					saleOrder.setPartnerNameBySeller(partner.getName());
					
					BigDecimal amount = FuncUtil.addSaleAmount(saleDetailsList);
					saleOrder.setAmount(amount);
					
					if( !insertPartnerToOrders(saleOrder.getPartnerIdBySeller(), saleOrder)) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL, false);
						return paramsMap;
					}
					
					dao.create(saleOrder);
					
					for(PurOrSaleOrderDetail details : saleDetailsList) {
						details.setOrdersId(saleOrder.getId());
					}
					
					int num = saleOrderDetailsDao.batchInsert(saleDetailsList);
					if(num != saleDetailsList.size()) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL, false);
						return paramsMap;
					}
					
//					String statusName = DictionaryResource.getDictionaryValue(
//							DictionaryEnum.GROUP_ORDER_STATUS, saleOrder.getStatus());
					
//					String remark = "销售商" + "向" + "采购方" + "销售了金额为" + saleOrder.getAmount() + "的货物";
//					taskEngineService.create(4, "orders", saleOrder.getId(), saleOrder.getCodeOfSeller(), Integer.parseInt(saleOrder.getStatus()), 
//							Integer.parseInt(saleOrder.getStatus()), statusName, remark);
					
//					Notice notice = new Notice();
//					notice.setSenderId(sellerId);
//					notice.setReceiverId(saleOrder.getBuyerId());
//					notice.setNoticeType(1);
//					notice.setTitle("title");
//					notice.setContent("content");
//					noticeService.create(notice);
					
					putCorrectMess(paramsMap, saleOrder.getId(), saleOrder.getStatus(), false);
					if(PurOrSaleOrder.STATUS_TMP.equals(saleOrder.getStatus())) {
						saleOrder.setActionId(BehaviourEnum.SAVE_NOT_ONLINE_SALEORDER.getActionId());
						saleOrder.setActionName(BehaviourEnum.SAVE_NOT_ONLINE_SALEORDER.getActionName());
					} else {
						saleOrder.setActionId(BehaviourEnum.SUBMIT_NOT_ONLINE_SALEORDER.getActionId());
						saleOrder.setActionName(BehaviourEnum.SUBMIT_NOT_ONLINE_SALEORDER.getActionName());
					}
					purOrSaleTaskService.saveOrders(saleOrder);
					
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			logger.error("销售订单新增时异常...", re);
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_INITIAL, false);
		}
		return mesMap;
	}
	
	private void setNewOrdersToOrders(PurOrSaleOrder sale, PurOrSaleOrder orders) {
		orders.setAreaId(sale.getAreaId());
		orders.setProvince(sale.getProvince());
		orders.setCity(sale.getCity());
		orders.setDistrict(sale.getDistrict());
		orders.setStreet(sale.getStreet());
		
		orders.setPhone(sale.getPhone());
		orders.setMobile(sale.getMobile());
		orders.setPostCode(sale.getPostCode());
		
		orders.setReceivedId(sale.getReceivedId());
		orders.setReceiverName(sale.getReceiverName());
		
		orders.setMemoOfSeller(sale.getMemoOfSeller());
		orders.setTransportType(sale.getTransportType());
		orders.setPaymentType(sale.getPaymentType());
		
		orders.setStatus(sale.getStatus());
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> updateSaleOrderAndDetails(final PurOrSaleOrder saleOrder, 
			final List<PurOrSaleOrderDetail> list_update, final List<PurOrSaleOrderDetail> list_add, 
				final List<Integer> list_all) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final String sellerName = se.getCompanyName();
		final Integer userId = se.getUserId();
		final String userName = se.getUserName();
		
		Map<String, Object> mesMap = null;
		
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();

					if( !PurOrSaleOrder.STATUS_TMP.equals(saleOrder.getStatus()) && 
							!PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())) {
						transactionStatus.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, null, true);
						return paramsMap;
					}
					
					
					
					paramsMap.put("id", saleOrder.getId());
					paramsMap.put("sellerId", sellerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if(isQueryException(orders, userId)) {
						transactionStatus.setRollbackOnly();
						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
						return paramsMap;
					}
					
					if( !PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus()) && 
							!PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(orders.getStatus())) {
						transactionStatus.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, null, true);
						return paramsMap;
					}
					
					setNewOrdersToOrders(saleOrder, orders);
					
					List<Integer> ids = saleOrderDetailsDao.getDetailsIdByOrderId(orders.getId());
					List<Integer> deleteIds = ListUtils.subtract(ids, list_all);
					int delNum = saleOrderDetailsDao.deleteBatch(deleteIds);
					if(delNum != deleteIds.size()) {
						transactionStatus.setRollbackOnly();
	//					paramsMap.clear();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					for(PurOrSaleOrderDetail d : list_update) {
						d.setOrdersId(orders.getId());
					}
					
					int updateNum = saleOrderDetailsDao.updateBatch(list_update);
					if(updateNum != list_update.size()) {
						transactionStatus.setRollbackOnly();
	//					paramsMap.clear();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					for(PurOrSaleOrderDetail d : list_add) {
						d.setOrdersId(orders.getId());
					}
					int add_num = saleOrderDetailsDao.batchInsert(list_add);
					if(add_num != list_add.size()) {
						transactionStatus.setRollbackOnly();
	//					paramsMap.clear();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					BigDecimal amount = saleOrderDetailsDao.getAmountByOrdersId(orders.getId());
					
					orders.setAmount(amount);
					
					if(PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(orders.getStatus())) {
						orders.setSubmitterId(userId);
						orders.setSubmitterName(userName);
						orders.setCurrentorId(null);
						orders.setCurrentorName(null);
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_SALE_ORDER.getWorkFlowId())) {
							orders.setCurrentCompanyId(orders.getBuyerId());
							orders.setCurrentCompanyName(orders.getBuyerName());
						}
					}
					
					boolean isOK = getDao().update(orders);
					
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					putCorrectMess(paramsMap, orders.getId(), orders.getStatus(), false);
					if(PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
						orders.setActionId(BehaviourEnum.UPDATE_NOT_ONLINE_SALEORDER.getActionId());
						orders.setActionName(BehaviourEnum.UPDATE_NOT_ONLINE_SALEORDER.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.UPDATE_AND_SUBMIT_NOT_ONLINE_SALEORDER.getActionId());
						orders.setActionName(BehaviourEnum.UPDATE_AND_SUBMIT_NOT_ONLINE_SALEORDER.getActionName());
					}
					purOrSaleTaskService.updateOrders(orders);
					
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_TMP, false);
			logger.error("修改消息订单时异常...", re);
		}
		return mesMap;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> deleteSaleOrderAndDetails(final Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
				
		Map<String, Object> mesMap = null;
		try {
		mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				
				paramsMap.put("id", saleOrderId);
				paramsMap.put("sellerId", sellerId);
				
				PurOrSaleOrder orders = (PurOrSaleOrder) getDao().getById(paramsMap);
				paramsMap.clear();
				
				if(isQueryException(orders, userId)) {
					status.setRollbackOnly();
					putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
					return paramsMap;
				}
				
				if( !PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
					status.setRollbackOnly();
					putSaleOrderModifyExceptionMess(paramsMap, null, true);
					return paramsMap;
				}
				
				boolean isOK = getDao().deleteById(saleOrderId);
				
				if( !isOK ) {
					status.setRollbackOnly();
					putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
					return paramsMap;
				}
				
//				saleOrderDetailsDao.deleteDetailsByOrdersId(saleOrderId);
				
				putCorrectMess(paramsMap, saleOrderId, orders.getStatus(), true);
				
				orders.setStatus(PurOrSaleOrder.STATUS_DELETED);
				orders.setActionId(BehaviourEnum.DELETE_NOT_ONLINE_SALEORDER.getActionId());
				orders.setActionName(BehaviourEnum.DELETE_NOT_ONLINE_SALEORDER.getActionName());
				purOrSaleTaskService.deleteOrders(orders);
								
				return paramsMap;
			}
		});
		} catch(RuntimeException re) {
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_TMP, false);
			logger.error("删除销售订单时异常...", re);
		}
		return mesMap;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> dealSaleOrder(final Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		final String userName = se.getUserName();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					
					paramsMap.put("id", saleOrderId);
					paramsMap.put("sellerId", sellerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if(orders == null || 
							!PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
						status.setRollbackOnly();
						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
						return paramsMap;
					}
					
//					if(isQueryException(orders, userId)) {
//						status.setRollbackOnly();
//						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
//						return paramsMap;
//					}
					
//					if( !PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
//						status.setRollbackOnly();
//						putSaleOrderModifyExceptionMess(paramsMap, null, true);
//						return paramsMap;
//					}
					
					paramsMap.put("id", orders.getId());
					paramsMap.put("currentorId", userId);
					paramsMap.put("currentorName", userName);
					boolean isOK = getDao().updateSaleOrderCurrentor(paramsMap);
					paramsMap.clear();
					
					if( !isOK ) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					putCorrectMess(paramsMap, orders.getId(), orders.getStatus(), false);
					
					orders.setCurrentorId(userId);
					orders.setCurrentorName(userName);
					orders.setActionId(BehaviourEnum.UPDATE_CURRENTOR_NOT_ONLINE_SALEORDER.getActionId());
					orders.setActionName(BehaviourEnum.UPDATE_CURRENTOR_NOT_ONLINE_SALEORDER.getActionName());
					purOrSaleTaskService.dealWithOrders(orders);
					
					return paramsMap;
				}
			});
		} catch (RuntimeException re) {
			logger.error("接手订单时异常...", re);
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_TMP, false);
		}
		return mesMap;
	}
	
	private Object checkPartnerAndAddress(PurOrSaleOrder saleOrder, Map<String, Object> paramsMap) {
//		if( !saleOrder.getWorkFlowId().equals(WorkFlowTaskNameEnum.
//				WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
//			return -2;
//		}
		
		Integer buyerId = saleOrder.getBuyerId();
		Company buyer = (Company) companyDao.getById(buyerId);
		if(buyer == null || buyer.getPaid() == Company.PAID_NO) {
			logger.error("采购公司不存在或未付费...");
			return -1;
		}
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer sellerId = se.getCompanyId();
		
		Partner partner = null;
		paramsMap.put("ownerId", sellerId);
		
		if(buyer.getRealType() == Company.AUTHENTICATION_TYPE_COMPANY ) {
			paramsMap.put("taxCode", buyer.getTaxCode());
			partner = partnerDao.getPartnerByTaxCode(paramsMap);
			if(partner == null) {
				logger.info("根据税号查找业务伙伴不存在");
			}
		} else {
			paramsMap.put("contactorIdentityCode", buyer.getContactorIdentityCode());
			List<Partner> p= partnerDao.getPartnerByIdent(paramsMap);
			if(p.size() == 0) {
				logger.info("根据身份证查找业务伙伴不存在");
			}
		}
		
		if(partner == null) {
			return 0;
		}
		
		
		
		if(partner.getCompanyId() != 0 && partner.getCompanyId() != null) {
			
			
			
			paramsMap.clear();
			paramsMap.put("ownerId", buyer.getId());
			paramsMap.put("companyId", sellerId);
			List<Partner> buyerPartners = partnerDao.getPartnersByConditions(paramsMap);
			
			if(buyerPartners.size() != 1) {
				logger.error("查找采购方业务伙伴找到" + buyerPartners.size() + "个");
				throw new RuntimeException("查找采购方业务伙伴找到" + buyerPartners.size() + "个");
			}
			
//			Partner buyerPartner = buyerPartners.get(0);
			
//			List<ReceiptAddress> reAddresslist = receiptAddressDao.getReceiptAddressListByCompId(buyerId);
//			
//			ReceiptAddress receiptAddress = null;
//			for(ReceiptAddress _receiptAddress : reAddresslist) {
//				if(_receiptAddress.getAreaId().equals(saleOrder.getAreaId())) {
//					receiptAddress = _receiptAddress;
//					break;
//				}
//			}
//			
//			List<PartnerAddress> ptAddressList = partnerAddressDao.getPartnerAddressByPartnerId(partner.getId());
//			
//			for(PartnerAddress _partnerAddress : ptAddressList) {
//				if(receiptAddress.getAreaId().equals(_partnerAddress.getAreaId())) {
////					if()
//				}
//			}
			
			return 1;
		}
		
		/**
		 * ...
		 */
		
		partnerAddressDao.getPartnerAddressByCondition(paramsMap);
		
		
		
		return partner;
		
	}
	
	private void compare(List<ReceiptAddress> reAddresslist, List<PartnerAddress> ptAddressList) {
		
	}
	
	private Map<String, Object> checkPartnerMess(PurOrSaleOrder saleOrder, Map<String, Object> paramsMap) {
		
		Object obj = checkPartnerAndAddress(saleOrder, paramsMap);
		if(obj.equals(-2)) {
			paramsMap.put(Params.SALE_ALERT_MES, "错误提示:您不可以使用该流程");
			paramsMap.put("open", "0");
			paramsMap.put("sel", "0");
		} else if(obj.equals(-1)) {
			paramsMap.put(Params.SALE_ALERT_MES, "错误提示:采购公司不存在或您未付费");
			paramsMap.put("open", "0");
			paramsMap.put("sel", "0");
		} else if(obj.equals(0)) {
			paramsMap.put(Params.SALE_ALERT_MES, "错误提示:您还没有建立该业务伙伴, 是否现在建立?");
			paramsMap.put("open", "0");
			paramsMap.put("sel", "1");
			paramsMap.put("ownerId", saleOrder.getSellerId());
			paramsMap.put("companyId", saleOrder.getBuyerId());
		} else if(obj.equals(1)) {
//			paramsMap.put(Params.SALE_ALERT_MES, "您可以使用该流程");
//			paramsMap.put("open", "0");
		} else {
			Partner partner = (Partner)obj;
			paramsMap.put(
					Params.SALE_ALERT_MES, "信息提示:业务伙伴信息[名称：" + partner.getName() + 
					(partner.getTaxCode() == null ? "" : ";税号：" + partner.getTaxCode()) +
					";地址：" + partner.getAddress() + 
					(partner.getContactorIdentityCode() == null ? "" : ";负责人身份证：" + partner.getContactorIdentityCode()) + "]" + 
					"  以上信息已经过期，您确定更新吗？"
			);
			paramsMap.put("open", "0");
			paramsMap.put("sel", "1");
			paramsMap.put("ownerId", saleOrder.getSellerId());
			paramsMap.put("companyId", saleOrder.getBuyerId());
		}
		return paramsMap;
	}
	
	public Map<String, Object> toShowSaleOrderById(Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		
		paramsMap.put("id", saleOrderId);
		paramsMap.put("sellerId", sellerId);
		PurOrSaleOrder saleOrder =  (PurOrSaleOrder) getById(paramsMap);
		paramsMap.clear();
		
//		if(isQueryException(saleOrder, userId)) {
//			putSaleOrderQueryExceptionMess(paramsMap, saleOrder, userId);
//		} else if(needTakeOver(saleOrder, userId)) {
//			putTakeOverMess(paramsMap, saleOrder, userId);
//		} else {
//			putCorrectMess(paramsMap, saleOrderId, saleOrder.getStatus(), false);
//		}
		
		
		SaleOrderServiceUtil.toShowOrders(paramsMap, saleOrder);
		
		
		/*if(saleOrder.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_SALE_ORDER.getWorkFlowId())) {
			return paramsMap;
		}*/
		
		/*Map<String, Object> parMap = new HashMap<String, Object>();
		parMap = checkPartnerMess(saleOrder, parMap);
		if(parMap.get("open").equals("0")) {
			paramsMap.clear();
			paramsMap.put(Params.SALE_ALERT_MES, parMap.get(Params.SALE_ALERT_MES));
			paramsMap.put("open", "0");
			paramsMap.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
		}*/
				
		return paramsMap;
	}
	
	public Map<String, Object> loadSaleOrderById(Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
//		final Integer userId = se.getUserId();
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("id", saleOrderId);
		paramsMap.put("sellerId", sellerId);
		
		paramsMap = getDao().loadSaleOrderById(paramsMap);
		
		String statusDes = DictionaryResource.getDictionaryValue(DictionaryEnum.GROUP_ORDER_STATUS, paramsMap.get("status").toString());
		paramsMap.put("statusDes", statusDes);
		
		return paramsMap;
	}
	
	public List<Map<String, Object>> loadDetailsBySaleOrderId(Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
//		final Integer userId = se.getUserId();
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("ordersId", saleOrderId);
		paramsMap.put("sellerId", sellerId);
		
		List<Map<String, Object>> list = this.saleOrderDetailsDao.loadDetailsByOrdersId(paramsMap);
		
		return list;
	}
	
	/**
	 * 按照概要浏览
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> querySaleOrdersListByComplex(Map<String, Object> paramsMap) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer sellerId = se.getCompanyId();
		paramsMap.put("sellerId", sellerId);
		
		Integer totalProperty = this.getDao().querySaleOrdersListCountByComplex(paramsMap);
		List<Map<String, Object>> list = this.getDao().querySaleOrdersListByComplex(paramsMap);
		
		for(Map<String, Object> map : list) {
			String statusDes = DictionaryResource.getDictionaryValue(
					DictionaryEnum.GROUP_ORDER_STATUS, map.get("status").toString());
			map.put("statusDes", statusDes);
			if(map.get("partnerNameBySeller") == null || 
					map.get("partnerNameBySeller").toString().trim().equals("")) {
				map.put("partnerNameBySeller", map.get("buyerName"));
			}
		}

		paramsMap.clear();
		paramsMap.put("totalProperty", totalProperty);
		paramsMap.put("root", list);
		
		return paramsMap;
	}
	
	/**
	 * 按照明细浏览
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> querySaleDetailsListByComplex(Map<String, Object> paramsMap) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer sellerId = se.getCompanyId();
		paramsMap.put("sellerId", sellerId);
				
		Integer totalProperty = saleOrderDetailsDao.querySaleDetailsListCountByComplex(paramsMap);
		List<Map<String, Object>> list = saleOrderDetailsDao.querySaleDetailsListByComplex(paramsMap);
		
		paramsMap.clear();
		paramsMap.put("totalProperty", totalProperty);
		paramsMap.put("root", list);
		
		return paramsMap;
	}
	
	/**
	 * 我来处理采购订单
	 * @param saleOrderId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> takeOverOrders(final Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		final String userName = se.getUserName();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
										
					paramsMap.put("sellerId", sellerId);
					paramsMap.put("id", saleOrderId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if(isQueryException(orders, null)) {
						status.setRollbackOnly();
						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
						return paramsMap;
					} 
					
					if( !PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus())) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, null, true);
						return paramsMap;
					}
					
					paramsMap.put("id", orders.getId());
					if(orders.getCodeOfSeller() == null) {
						String codeOfSeller = codeGenericDao.getNewCode(sellerId, CodeGeneric.SALE_ORDER);
						paramsMap.put("codeOfSeller", codeOfSeller);
						orders.setCodeOfSeller(codeOfSeller);
					}
					
					paramsMap.put("takeoverId", userId);
					paramsMap.put("takeoverName", userName);
					paramsMap.put("currentorId", userId);
					paramsMap.put("currentorName", userName);
					boolean isOK = getDao().takeOverPurchaseOrder(paramsMap);
					paramsMap.clear();
					
					if( !isOK ) {
						status.setRollbackOnly();
						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
						return paramsMap;
					}
					
					putCorrectMess(paramsMap, orders.getId(), orders.getStatus(), false);
					
					orders.setCurrentorId(userId);
					orders.setCurrentorName(userName);
					orders.setActionId(BehaviourEnum.TAKEOVER_ONLINE_PURCHASEORDER.getActionId());
					orders.setActionName(BehaviourEnum.TAKEOVER_ONLINE_PURCHASEORDER.getActionName());
					purOrSaleTaskService.takeOverOrders(orders);
					
					return paramsMap;
				}
			});
		} catch (RuntimeException re) {
			mesMap = new HashMap<String, Object>();
			logger.error("我来处理采购订单时异常...", re);
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT + "-", false);
		}
				
		return mesMap;
		
	}
	
	/**
	 * 操作正确时返回信息
	 * @param map
	 * @param saleOrderId
	 * @param status
	 * @param isRemoved
	 */
	private void putCorrectMess(Map<String, Object> map, Integer saleOrderId, String status, boolean isRemoved) {
		
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_OK.getKey());
		
		if(isRemoved) {
			map.put(Params.ORDERS_REMOVE_PARAM, Params.ORDERS_REMOVE_YES_STRING);
			map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
		} else {
			map.put(Params.SALE_ORDER_STATUS_PARAM, status);
			map.put(Params.SALE_ORDER_ID_PARAM, saleOrderId);
			map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_SALE_FORM.getKey() + ":" 
					+ SaleOrderFunctionEnum.lOAD_DETAILS_GRID.getKey() + ":" 
					+ SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey() 
			);
		}
	}
	

	/**
	 * 封装修改记录时出现的异常信息
	 * @param map
	 * @param status
	 */
//	private void putSaleOrderModifyExceptionMess(Map<String, Object> map) {
////		map.put(Params.SALE_ORDER_STATUS_PARAM, status);
//		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_ERROR.getKey());
////		map.put("remove", "0");
////		map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
//	}
	
	private boolean needTakeOver(PurOrSaleOrder saleOrder, Integer userId) {
		if(PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(saleOrder.getStatus()) ) {
			if(saleOrder.getCurrentorId() == null || !saleOrder.getCurrentorId().equals(userId)) {
				return true;
			}
		}
		return false;
	}
	
	private void putTakeOverMess(Map<String, Object> map, PurOrSaleOrder saleOrder, Integer userId) {
//		if(PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(saleOrder.getStatus())) {
//		} 
		if(userId.equals(saleOrder.getCurrentorId())) {
			map.put(Params.SALE_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT);
		} else {
			map.put(Params.SALE_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT + "-");
		}
		
		map.put(Params.SALE_ORDER_ID_PARAM, saleOrder.getId());
		map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_SALE_FORM.getKey()  + ":" 
											+ SaleOrderFunctionEnum.lOAD_DETAILS_GRID.getKey() + ":" 
											+ SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey() 
											);
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_OK.getKey());
	}
	
	/**
	 * 查询销售订单时是否非正常信息
	 * @param saleOrder
	 * @param userId
	 * @return
	 */
	private boolean isQueryException(PurOrSaleOrder saleOrder, Integer userId) {
		if(saleOrder == null) {
			return true;
		} else if(saleOrder.getStatus().equals(PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT)) {
			return false;
		} else if( 
//				PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(saleOrder.getStatus())
//				|| 
				PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())
				|| PurOrSaleOrder.STATUS_AGREE_TO_RECIEVE.equals(saleOrder.getStatus()) 
				|| PurOrSaleOrder.STATUS_SELLER_DELIVERY.equals(saleOrder.getStatus()) 
				|| PurOrSaleOrder.STATUS_BUYER_ACPT.equals(saleOrder.getStatus())) {
			return true;
		} else if ( userId != null && !userId.equals(saleOrder.getCurrentorId()) ) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 封装修改记录时出现的异常信息
	 * @param map
	 * @param status
	 * @param isRemoved
	 */
	private void putSaleOrderModifyExceptionMess(Map<String, Object> map, String status, boolean isRemoved) {
		
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_ERROR.getKey());
		
		if(isRemoved) {
			map.put(Params.ORDERS_REMOVE_PARAM, Params.ORDERS_REMOVE_YES_STRING);
			map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
		} else {
			map.put(Params.SALE_ORDER_STATUS_PARAM, status);
			map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
		}
	}
	
	/**
	 * 查询销售订单时封装非正常信息
	 * @param map
	 * @param saleOrder
	 * @param userId
	 */
	private void putSaleOrderQueryExceptionMess(Map<String, Object> map, PurOrSaleOrder saleOrder, Integer userId) {
		if(saleOrder == null) {
			putOrderIsNullMess(map);
		} else if( 
//				PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(saleOrder.getStatus())
//				|| 
				PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())
				|| PurOrSaleOrder.STATUS_SELLER_DELIVERY.equals(saleOrder.getStatus())
				|| PurOrSaleOrder.STATUS_AGREE_TO_RECIEVE.equals(saleOrder.getStatus())
				|| PurOrSaleOrder.STATUS_BUYER_ACPT.equals(saleOrder.getStatus())) {
			putSubmittedMess(map, saleOrder.getId(), saleOrder.getStatus());
		} else if( !userId.equals(saleOrder.getCurrentorId()) ) {
			putNotCurrentorMess(map, saleOrder.getId());
		} else {
			throw new RuntimeException("判断销售订单是否符合查询条件时抛异常...");
		}
	}
	
	/**
	 * 单据不存在
	 * @param map
	 */
	private void putOrderIsNullMess(Map<String, Object> map) {
		map.put(Params.ORDERS_REMOVE_PARAM, Params.ORDERS_REMOVE_YES_STRING);
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_NOT_EXIST.getKey());
		map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
		
//		map.put(Params.SALE_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_INITIAL);
	}
	
	/**
	 * 单据已经提交
	 * @param map
	 * @param saleOrderId
	 * @param status
	 */
	private void putSubmittedMess(Map<String, Object> map, Integer saleOrderId, String status) {
		map.put(Params.SALE_ORDER_STATUS_PARAM, status);
		map.put(Params.SALE_ORDER_ID_PARAM, saleOrderId);
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_SUBMIT.getKey());
		map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_SALE_FORM.getKey()  + ":" 
											+ SaleOrderFunctionEnum.lOAD_DETAILS_GRID.getKey() + ":" 
											+ SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey() 
											);
	}
	
	/**
	 * 单据不是当前处理人
	 * @param map
	 * @param saleOrderId
	 */
	private void putNotCurrentorMess(Map<String, Object> map, Integer saleOrderId) {
		map.put(Params.SALE_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_TMP + "-");
		map.put(Params.SALE_ORDER_ID_PARAM, saleOrderId);
		map.put(Params.SALE_ALERT_MES, SaleOrderOperateMesEnum.ORDERS_NOT_CURRENT_USER.getKey());
		map.put(Params.SALE_LOADED_MESS_KEYS, SaleOrderFunctionEnum.LOAD_SALE_FORM.getKey() + ":" 
											+ SaleOrderFunctionEnum.lOAD_DETAILS_GRID.getKey() + ":" 
											+ SaleOrderFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey() 
											);
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> takeOverUpdateOrSubmit(final PurOrSaleOrder saleOrder, final List<PurOrSaleOrderDetail> list_update,
			final List<PurOrSaleOrderDetail> list_add, final List<Integer> list_all) {
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					
//					if( !PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(saleOrder.getStatus()) && 
//							!PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(saleOrder.getStatus())) {
//						status.setRollbackOnly();
//						putSaleOrderModifyExceptionMess(paramsMap, null, true);
//						return paramsMap;
//					}
					
					paramsMap.put("id", saleOrder.getId());
					paramsMap.put("sellerId", sellerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder)getById(paramsMap);
					paramsMap.clear();
					
					orders.setPaymentType(saleOrder.getPaymentType());
					orders.setTransportType(saleOrder.getTransportType());
					orders.setMemoOfSeller(saleOrder.getMemoOfSeller());
					
					update(orders);
					
//					if(isQueryException(orders, userId)) {
//						status.setRollbackOnly();
//						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
//						return paramsMap;
//					}
					
//					if( !PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus()) && 
//							!PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(orders.getStatus()) ){
//						status.setRollbackOnly();
//						putSaleOrderModifyExceptionMess(paramsMap, null, true);
//						return paramsMap;
//					}
					
//					orders.setStatus(saleOrder.getStatus());
//					if(PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY.equals(orders.getStatus())) {
//						orders.setCurrentorId(null);
//						orders.setCurrentorName(null);
//					}
					
					List<Integer> ids = saleOrderDetailsDao.getDetailsIdByOrderId(orders.getId());
					List<Integer> deleteIds = ListUtils.subtract(ids, list_all);
					int delNum = saleOrderDetailsDao.deleteBatch(deleteIds);
//					if(delNum != deleteIds.size()) {
//						status.setRollbackOnly();
////						paramsMap.clear();
//						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
//						return paramsMap;
//					}
					
					for(PurOrSaleOrderDetail d : list_update) {
						d.setOrdersId(orders.getId());
					}
					
					int updateNum = saleOrderDetailsDao.updateBatch(list_update);
//					if(updateNum != list_update.size()) {
//						status.setRollbackOnly();
////						paramsMap.clear();
//						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
//						return paramsMap;
//					}
					
					for(PurOrSaleOrderDetail d : list_add) {
						d.setOrdersId(orders.getId());
					}
					int add_num = saleOrderDetailsDao.batchInsert(list_add);
//					if(add_num != list_add.size()) {
//						status.setRollbackOnly();
////						paramsMap.clear();
//						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
//						return paramsMap;
//					}
					
					BigDecimal amount = saleOrderDetailsDao.getAmountByOrdersId(orders.getId());
					
					orders.setAmount(amount);
					
					orders.setStatus(saleOrder.getStatus());
					
					boolean isOK = getDao().update(orders);
//					if( !isOK ) {
//						status.setRollbackOnly();
////						paramsMap.clear();
//						putSaleOrderModifyExceptionMess(paramsMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
//						return paramsMap;
//					}
					
//					paramsMap.clear();
					putCorrectMess(paramsMap, orders.getId(), orders.getStatus(), false);
					
					
					if(PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus())) {
						orders.setActionId(BehaviourEnum.TAKEOVER_TO_UPDATE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.TAKEOVER_TO_UPDATE_PURCHASEORDER.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.TAKEOVER_TO_UPDATE_TO_SUBMIT_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.TAKEOVER_TO_UPDATE_TO_SUBMIT_PURCHASEORDER.getActionName());
					}
					
					purOrSaleTaskService.takeOverUpdateOrders(orders);
					
					return paramsMap;
				}
			});
		} catch (RuntimeException re) {
			logger.error("处理对方采购订单修改时异常...", re);
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
		}
		
		return mesMap;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> turnBackPurchaseOrder(final Integer saleOrderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer sellerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status) {
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("sellerId", sellerId);
					paramsMap.put("id", saleOrderId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
//					if(orders == null) {
//						status.setRollbackOnly();
//						putSaleOrderQueryExceptionMess(paramsMap, orders, userId);
//						return paramsMap;
//					} 
					
//					if( !PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus()) ) {
//						status.setRollbackOnly();
//						putSaleOrderModifyExceptionMess(paramsMap, null, true);
//						return paramsMap;
//					}
					
					paramsMap.put("id", saleOrderId);
					paramsMap.put("status", PurOrSaleOrder.STATUS_INVALIDE);
					boolean isOK = getDao().turnBackPurchaseOrder(paramsMap);
					paramsMap.clear();
					
//					if( !isOK ) {
//						status.setRollbackOnly();
//						putSaleOrderModifyExceptionMess(paramsMap, orders.getStatus(), false);
//						return paramsMap;
//					}
					
					orders.setStatus(PurOrSaleOrder.STATUS_INVALIDE);
					
					putCorrectMess(paramsMap, saleOrderId, orders.getStatus(), false);
					
					orders.setCurrentorId(null);
					orders.setCurrentorName(null);
					orders.setActionId(BehaviourEnum.TURNBACK_PURCHASEORDER.getActionId());
					orders.setActionName(BehaviourEnum.TURNBACK_PURCHASEORDER.getActionName());
					
					purOrSaleTaskService.turnBack(orders);
					
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			logger.error("回退采购订单时出错...", re);
			mesMap = new HashMap<String, Object>();
			putSaleOrderModifyExceptionMess(mesMap, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT, false);
		}
		
		return mesMap;
	}
	
	/**
	 * 销售发货引用
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> getAvailableOrdersMess(Map<String, Object> paramsMap) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer sellerId = se.getCompanyId();
		
		paramsMap.put("sellerId", sellerId);
		paramsMap.put("status", PurOrSaleOrder.STATUS_WAIT_SELLER_DELIVERY);
		
		List<Map<String, Object>> list = getDao().querySaleOrdersListByComplex(paramsMap);
		Integer totalProperty = getDao().querySaleOrdersListCountByComplex(paramsMap);
		
		paramsMap.clear();
		paramsMap.put("root", list);
		paramsMap.put("totalProperty", totalProperty);
		
		return paramsMap;
	}

	public boolean updateSaleOrderCurrentorById(Integer id) {
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentorId", sm.getUserId());
		map.put("currentorName", sm.getUserName());
		map.put("id", id);
		map.put("sellerId", sm.getCompanyId());		
		boolean success = getDao().updateSaleOrderCurrentor(map);
		return success;		
	}
	
	public boolean sale(Integer ordersId) {
		PurOrSaleOrder orders = (PurOrSaleOrder) getById(ordersId);
		return purOrSaleTaskService.sale(orders );
	}
}
